from urllib import parse, request

# 获取要查询的url
def getUrl(word:object)->object:
    # 定义搜索的主网址并设置格式
    url = 'https://www.baidu.com/s?{}'
    # 对接受参数进行编码格式配置格式
    params = parse.urlencode({'wd': word})
    # 拼接url
    url = url.format(params)
    return url

# 解析url
def requestURL(url)->object:
    # 设置伪代理
    headers = {
        'User-Agent': 'Mozilla/5.0 (Macintosh; Inter Mac OS X 10.12; rv:65) Gecko/20100101 Firefox/65.0'
    }
    # 配置请求信息
    reqm = request.Request(url=url, headers=headers)
    # 打开地址获取信息
    res = request.urlopen(reqm)
    # 对获取信息进行格式化
    myHtml = res.read().decode('utf-8')
    # print(myHtml)
    return myHtml
# 保存抓取的数据
def saveHtml(html,filename):
    # print(html)
    with open(filename, 'w', encoding='utf-8') as f:
        f.write(html)

if __name__ == '__main__':
    print("完成通过控制台爬取相关数据")
    str = input("请输入要检索的内容：")
    myUrl = getUrl(str)
    saveHtml(requestURL(myUrl), "my.html")
